#include "BSUtility.h"
#include "BlueprintScriptLibrary/Var.h"
#include "BaseInc_BlueprintScript.h"
#include <filesystem>
namespace fs = std::filesystem;
VarBaseBool BSUtility::HitTest(Vec2vbi point, Vec2vbi pos, Vec2vbi size)
{
	if (point.x.val >= pos.x.val && point.x.val <= pos.x.val + size.x.val)
	{
		if (point.y.val >= pos.y.val && point.y.val <= pos.y.val + size.y.val)
		{
			return VarBaseBool(true);
		}
	}

	return VarBaseBool();
}

void BSUtility::SearchDir(const std::string& path, std::vector<std::string>& vctFileList)
{
	try {
		if (fs::exists(path) && fs::is_directory(path)) {
			for (const auto& entry : fs::directory_iterator(path)) {
				std::string childPath = entry.path().string();
				if (fs::is_regular_file(entry.status())) {
					int r = childPath.rfind(".bp");
					if (childPath.rfind(".bp") != std::string::npos)
					{
						std::cout << entry.path() << "r:" << childPath[r] << std::endl;
						//files.push_back(path);
						vctFileList.push_back(childPath);
					}
					else {
						std::cout << entry.path() << " bp:" << childPath.rfind(".bp") << std::endl;
					}
				}
				else if (fs::is_directory(entry.status()))
				{
					SearchDir(childPath, vctFileList);
				}
			}
		}
		else {
			std::cerr << "Path does not exist or is not a directory." << std::endl;
		}
	}
	catch (const fs::filesystem_error& e) {
		std::cerr << e.what() << std::endl;
	}
}

std::string BSUtility::SubToStr(const std::string& src, std::string sub, bool bRecursive, bool bSubFromFront)
{
	//int r = childPath.rfind(".bp");
	//if (childPath.rfind(".bp") != std::string::npos)
	//{
	//	std::cout << entry.path() << "r:" << childPath[r] << std::endl;
	//files.push_back(path);
	//	vctFileList.push_back(childPath);
	//}
	//else {
	//	std::cout << entry.path() << " bp:" << childPath.rfind(".bp") << std::endl;
	//}
	std::string result;
	size_t sd = src.rfind(sub);
	if (sd != std::string::npos)
	{
		if (bSubFromFront) {
			result = src.substr(sd + 1);
		}
		else {
			result = src.substr(0, sd);
		}
		if (bRecursive) {
			result = SubToStr(result, sub, bRecursive, bSubFromFront);
		}
	}
	else {
		result = src;
	}
	return result;
}

std::string BSUtility::ConvertBpFileClsName(std::string nstr)
{
		//.\\bp\\clsB\\MyClassB.bp
		size_t pos = nstr.find_first_of("./");
		if (std::string::npos == pos) {
			return "";
		}
		nstr = nstr.substr(pos+2);
		pos = nstr.find_last_of(".");
		nstr = nstr.substr(0, pos);
		std::cout << nstr << std::endl;
		std::string clsName = "";
		while (pos != std::string::npos) {
			pos = nstr.find("\\");
			std::cout << nstr.substr(0, pos) << std::endl;
			clsName += nstr.substr(0, pos);
			nstr = nstr.substr(pos+1);
			if (pos != std::string::npos) {
				clsName += ".";
			}
		}
		return clsName;
}
